/**
 * @description 功能-控制器
 * @since 2019-11-12
 * @author Rid King
*/

const ox = require('@daelui/oxjs')
const request = require('request')

class Controller extends ox.Controller {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
  }

  // 页面
  page (action) {
    const req = action.req, res = action.res
    const path = req.url.replace(/^\/+/, '') //.replace(/.+\/tigerlair\/saas\/snuxt/i, '')
    try {
      if (req.headers.accept === 'text/event-stream') {
        res.setHeader('content-type', 'text/event-stream;charset=utf-8')
        res.status(200).send('"data": {"event": "ok"}')
        return
      }
      request({
        uri: 'http://localhost:3604' + '/' + path,
        method: req.method,
        body: req.body,
        headers: req.headers,
        timeout: 30000
      }, (error, response, body) => {
        if (response) {
          let headers = response.headers || {}
          for (let key in headers) {
            res.setHeader(key, response.headers[key])
          }
          if (error) {
            console.error('转发请求时发生错误:', error)
            return res.status(500).send('请求失败')
          }
          res.status(response.statusCode).send(body)
        } else {
          if (req.headers.accept === 'text/event-stream') {
            res.setHeader('content-type', 'text/event-stream;charset=utf-8')
          }
          res.status(200).send('"data": {"event": "ok"}')
        }
      })
    } catch(e) {
      if (req.headers.accept === 'text/event-stream') {
        res.setHeader('content-type', 'text/event-stream;charset=utf-8')
      }
      res.status(200).send('"data": {"event": "ok"}')
    }

    return 'EXIT'
  }
}

module.exports = Controller